<?php
/**
 * Note: *
 * Date: 2020/2/24
 */
namespace App\Http\Controllers\Admin;

use App\Console\Commands\CacheReset;
use App\Models\Role;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;

class RoleController extends CurdController
{
    protected string $classModel = Role::class;

    protected array $relationWiths = [
        'roleAccess',
        'creator'
    ];

    protected array $searchFields = [];


    public function index(Request $request)
    {
        // 非超管只能看见自己创建的角色
        if (!in_array(1, $this->user->role)) {
            $this->searchFields = ['creator_id'];
            $this->request->creator_id = $this->user->id;
        }

        return $this->myIndex();
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->request->merge(['creator_id' => $this->user->id]);
        $request->validate([
            'access' => 'sometimes|array',
        ]);
        if (!$role = Role::create($request->all())) {
            return responseException(__('web.failed'));
        }
        if ($request->access) $role->roleAccess()->attach($request->access);
        // 重置权限缓存
        Artisan::call(CacheReset::class);
        return responseMessage();
    }

    /**
     * @param Request $request
     * @param Role $role
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function update(Request $request, Role $role)
    {
        $request->validate([
            'access' => 'sometimes|array',
        ]);
        if (!$role->update($request->all())) {
            return responseException(__('web.failed'));
        }
        $role->roleAccess()->sync($request->access);
        // 重置权限缓存
        Artisan::call(CacheReset::class);
        return responseMessage();
    }

    /**
     * @param Model $data
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    protected function destroyBefore(Model $data)
    {
        if ($data->id < 2) {
            return responseException(__('auth.cant_delete_super_admin'));
        }
        // 重置权限缓存
        Artisan::call(CacheReset::class);
    }
}
